﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using SangsTools;
using Item;

namespace UI
{
    public class UIScience : MonoBehaviour
    {
        public static UIScience Ins { get; private set; }

        private bool _isOpen = false;
        public bool IsOpen {
            get => _isOpen;
            set
            {
                _isOpen = value;

                gameObject.SetActive(_isOpen);
            }
        }

        private Player.Science ScienceIns => Player.MyPlayer.Ins.MyScience;

        private Button btnMakeSure;

        private Text _globalCoefficientText, _choseCoefficientText, _needScienceNumText, _scienceNumText;
        private Transform itemRoot, itemPrefab;
        private Dictionary<string, (Text text, Toggle toggle)> dicProjectItem;

        private List<string> listChoose=new List<string>();
        private int _needScience = 0;

        //科研完成的回调
        private ChooseUIHandler _popUpUIHandler;
        private STPopUpWindowData _popUpWindowData;
        private StringBuilder sb;

        private void Awake()
        {
            Ins = this;

            foreach (var btn in GetComponentsInChildren<Button>())
            {
                switch (btn.name)
                {
                    case "ExitButton":
                        btn.onClick.AddListener(OnExitBtnClick);
                        break;
                    case "MakeSureButton":
                        btnMakeSure = btn;
                        btn.onClick.AddListener(OnMakeTrueBtnClick);
                        break;
                }
            }

            foreach (var text in GetComponentsInChildren<Text>())
            {
                switch (text.name)
                {
                    case "GlobalCoefficientText":
                        _globalCoefficientText = text;
                        break;
                    case "ChoseCoefficientText":
                        _choseCoefficientText = text;
                        break;
                    case "NeedScienceNumText":
                        _needScienceNumText = text;
                        break;
                    case "ScienceNumText":
                        _scienceNumText = text;
                        break;
                }
            }

            itemRoot = GetComponentInChildren<GridLayoutGroup>().transform;
            itemPrefab = itemRoot.Find("Prefab");

            btnMakeSure.interactable = false;

            ScienceIns.EventOnCoefficientChange += RefreshUI;
            ScienceIns.EventOnNumChange += RefreshScienceNum;

            IsOpen = false;

            _popUpUIHandler = new ChooseUIHandler();
            sb = new StringBuilder();
        }
        public void Init()
        {
            dicProjectItem = new Dictionary<string, (Text text, Toggle toggle)>();

            //初始化科研项目
            foreach (var item in ScienceIns.ScienceData.dictPrejectData)
            {
                var obj = Instantiate(itemPrefab.gameObject);
                obj.transform.SetParent(itemRoot);

                Toggle toggle = obj.GetComponentInChildren<Toggle>();
                string tag = item.Key;
                toggle.onValueChanged.AddListener((active) =>
                {
                    if (active)
                        listChoose.Add(tag);
                    else
                        listChoose.Remove(tag);
                    RefreshUI();
                });
                dicProjectItem.Add(item.Key, (obj.GetComponentInChildren<Text>(),toggle ));
            }
            itemPrefab.gameObject.SetActive(false);

            RefreshUI();
        }

        private void RefreshUI()
        {
            //TODO 优化,不能每次都全部刷新
            _globalCoefficientText.text = ScienceIns.GlobalCoefficient.ToString();

            float chooseCoefficient = 0;
            for (int i = 0; i < listChoose.Count; i++)
            {
                chooseCoefficient += ScienceIns[listChoose[i]].curCoefficient;
            }
            //基础 * 全局系数 * 选中系数
            _needScience = (int)(chooseCoefficient * ScienceIns.GlobalCoefficient * ScienceIns.ScienceData.nBaseScienceNum);

            _choseCoefficientText.text = chooseCoefficient.ToString();
            _needScienceNumText.text = _needScience.ToString();

            //刷新每一项的需求
            foreach (var item in dicProjectItem)
            {
                var data = ScienceIns[item.Key];
                item.Value.text.text = $"{data.projectData.strProjectName}\nx{data.curCoefficient}";
            }

            RefreshScienceNum();
        }
        private void RefreshScienceNum()
        {
            _scienceNumText.text = ScienceIns.ScienceNum.ToString();

            //确认选项能不能点
            btnMakeSure.interactable = _needScience > 0 && _needScience <= ScienceIns.ScienceNum;
        }
        private void OnExitBtnClick()
        {
            IsOpen = false;
        }
        private void OnMakeTrueBtnClick()
        {
            if (_needScience <= ScienceIns.ScienceNum)
            {
                var getItem = ScienceIns.FinishProject(listChoose.ToArray());
                if (getItem != null)
                {
                    sb.Clear();

                    _popUpWindowData.strTitle = "科研完成";
                    _popUpWindowData.arrOptions = new string[getItem.Length];

                        sb.Append("可选道具:\n");
                    for (int i = 0; i < getItem.Length; i++)
                    {
                        string name = ItemDataMgr.Ins[getItem[i]]?.strItemName;

                        sb.Append(getItem[i]);
                        sb.Append('\t');
                        sb.Append(name);
                        sb.Append('\n');

                        _popUpWindowData.arrOptions[i] = getItem[i];
                    }

                    _popUpWindowData.strDes = sb.ToString();

                    UIPopUpWindow.ShowPopUpWindow(_popUpWindowData, _popUpUIHandler);
                    Ins.IsOpen = false;
                }
                else
                {
                    Debug.Log("获取道具异常");
                }
            }
        }
        private class ChooseUIHandler : IPopUpWindowEventHandler
        {
            public void OnChooseOption(int optionIndex, STPopUpWindowData uiData)
            {
                Player.MyPlayer.Ins.MyBackpack.GetItem(uiData.arrOptions[optionIndex]);

                Ins.IsOpen = true;
            }
        }
    }
}
